package com.example.demo.api;

import com.example.demo.game.MatchRequest;
import com.example.demo.game.MatchResponse;
import com.example.demo.game.Matcher;
import com.example.demo.game.OnlineUserManager;
import com.example.demo.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

//通过这个类来处理匹配功能的websocket请求

@Component
public class MatchAPI extends TextWebSocketHandler {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private Matcher matcher;

    @Override
    //连接之后
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //玩家上线，加入到onlineusermanager中
        System.out.println("connect");
        //1。先获取到当前用户的身份信息
        try {
            User user = (User) session.getAttributes().get("user");

            //2.先判定当前用户是否已经登录过（已经是在线状态）

            if (onlineUserManager.getFromGameHall(user.getUserid()) != null
             || onlineUserManager.getFromGameRoom(user.getUserid()) != null){
                //用户已经登录
                MatchResponse response = new MatchResponse();
                response.setOk(true);
                response.setReason("当前禁止多开");
                response.setMessage("repeatConnection");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
                //session.close();

                return;
            }
            //3.拿到身份信息后将玩家设置成在线状态
            onlineUserManager.enterGameHall(user.getUserid(),session);
            System.out.println("玩家加入匹配页面" + user.getUsername());
        }catch (NullPointerException e){
            System.out.println("[MatchAPI.afterConnectionEstablished] 当前用户未登录");
            /*e.printStackTrace();*/
            MatchResponse response = new MatchResponse();
            response.setOk(false);
            response.setReason("未登录，无法匹配");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }


    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

        //处理开始匹配和停止匹配请求
        User user = (User) session.getAttributes().get("user");
        //获取到客户端给服务器发送的数据
        String payload = message.getPayload();
        //当前数据载荷是一个JSON字符串，需要转换为Java对象,MatchRequest
        MatchRequest request = objectMapper.readValue(payload,MatchRequest.class);
        MatchResponse response = new MatchResponse();
        if (request.getMessage().equals("startMatch")){
            matcher.add(user);
            response.setOk(true);
            response.setMessage("startMatch");
        }else if (request.getMessage().equals("stopMatch")){
            matcher.remove(user);
            //移除之后返回移除成功的响应
            response.setOk(true);
            response.setMessage("stopMatch");
        }else {
            response.setOk(false);
            response.setReason("非法的匹配请求");
        }
        String jsonString = objectMapper.writeValueAsString(response);
        session.sendMessage(new TextMessage(jsonString));
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //玩家下线，从onlineUserManager中删除
        try {
            //1.获取到当前的用户信息
            User user = (User) session.getAttributes().get("user");
            WebSocketSession tmpSession = onlineUserManager.getFromGameHall(user.getUserid());
            if (tmpSession == session){
                onlineUserManager.exitGameHall(user.getUserid());
            }
            //如果玩家掉线，就移除匹配队列
            matcher.remove(user);
        }catch (NullPointerException e){
            System.out.println("[MatchPI handleTransportError] 当前用户未登录");
        }
    }

    @Override
    //断开连接之后
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //玩家下线，从onlineUserManager中删除
        try {
            User user = (User) session.getAttributes().get("user");
            // 判断是否同一个session来下线，防止多开禁止后误删
            WebSocketSession tmpSession = onlineUserManager.getFromGameHall(user.getUserid());
            if (tmpSession == session){
                onlineUserManager.exitGameHall(user.getUserid());
            }
            matcher.remove(user);
        }catch (NullPointerException e){
            System.out.println("[MatchPI afterConnectionClosed] 当前用户未登录");
            //已经关闭了，所以发送不了，会出现空指针
            /*MatchResponse response = new MatchResponse();
            response.setOk(false);
            response.setReason("未登录，无法匹配");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));*/
        }
    }
}
